/*
 * Copyright 2014 Jonathan Haas
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package app.grinreader.ui;

import android.content.Context;
import android.database.DataSetObservable;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import app.grinreader.R;
import app.grinreader.library.BookData;
import app.grinreader.library.Library;
import nl.siegmann.epublib.domain.Author;
import nl.siegmann.epublib.domain.Relator;

import java.util.List;

/**
 * @author Kappich Systemberatung
 * @version $Revision: 0000 $
 */
public class LibraryGridAdapter extends DataSetObservable implements ListAdapter {
    private Library library;
    private GridView gridView;
    private Context context;

    public LibraryGridAdapter(Context context, Library library, GridView gridView) {
        this.context = context;
        this.library = library;
        this.gridView = gridView;
        library.registerObserver(new DataSetObserver() {
            @Override
            public void onChanged() {
                LibraryGridAdapter.this.notifyChanged();
            }

            @Override
            public void onInvalidated() {
                LibraryGridAdapter.this.notifyInvalidated();
            }
        });
    }

    public boolean areAllItemsEnabled() {
        return true;
    }

    public boolean isEnabled(int position) {
        return true;
    }

    public void registerDataSetObserver(DataSetObserver observer) {
        super.registerObserver(observer);
    }

    public void unregisterDataSetObserver(DataSetObserver observer) {
        super.unregisterObserver(observer);
    }

    public int getCount() {
        return library.getBooks().size();
    }

    public String getItem(int position) {
        return library.getBooks().get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public boolean hasStableIds() {
        return false;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater systemService = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = convertView == null ? systemService.inflate(R.layout.book, parent, false) : convertView;
        String bookFile = getItem(position);
        BookData cache = library.getBookData(bookFile);
        List<Author> authors = cache.getAuthors();
        String title = cache.getTitle();
        Bitmap thumbnail = cache.getThumbnail();
        ((TextView)view.findViewById(R.id.title)).setText(title);
        ((TextView)view.findViewById(R.id.author)).setText(getAuthorString(authors));
        if(thumbnail != null){
            ((ImageView)view.findViewById(R.id.imageView)).setImageBitmap(thumbnail);
        }
        else {
            ((ImageView)view.findViewById(R.id.imageView)).setImageResource(android.R.drawable.sym_def_app_icon);
        }
        return view;
    }

    private String getAuthorString(List<Author> authors) {
        StringBuilder stringBuilder = new StringBuilder();
        for (Author author : authors) {
            if(author == null || author.getRelator() != Relator.AUTHOR){
                continue;
            }
            CharSequence authorToString = authorToString(author);
            if (authorToString  == null) continue;
            stringBuilder.append(authorToString).append('\n');
        }
        return stringBuilder.toString();
    }

    private CharSequence authorToString(Author author) {
        StringBuilder result = new StringBuilder();
        String firstname = author.getFirstname();
        String lastname = author.getLastname();
        if(lastname.isEmpty()) lastname = null;
        if(firstname.isEmpty()) firstname = null;
        if(lastname == null && firstname == null) return null;
        if(firstname != null){
            result.append(firstname);
            if(lastname != null){
                result.append(" ");
            }
        }
        if (lastname != null){
            result.append(lastname);
        }
        int i = result.indexOf(",");
        if(i == -1){
            return result;
        }
        else {
            StringBuilder tmp = new StringBuilder();
            tmp.append(result.subSequence(i + 1, result.length()));
            tmp.append(" ");
            tmp.append(result.subSequence(0,i));
            return tmp;
        }
    }

    public int getItemViewType(int position) {
        return 0;
    }

    public int getViewTypeCount() {
        return 1;
    }

    public boolean isEmpty() {
        return getCount() != 0;
    }
}
